//
//  SEGActivityLotteryViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/15.
//  Copyright © 2017年 陈区. All rights reserved.
//
// 抽奖类

#import "SEGActivityLotteryViewController.h"
#import "SEGActivityLotteryTurnTableCell.h"
#import "SEGActivityLotteryBreakEggsCell.h"
#import "SEGActivityLotteryWinRecordCell.h"
#import "SEGActivityLotteryRankListCell.h"
#import "SEGWinRecordListViewController.h"
#import "SEGAlerViewHUD.h"
#import <SEGModel/SEGActivityLotteryDetailModel.h>
#import <SEGModel/SEGActivityLotteryResultModel.h>

@interface SEGActivityLotteryViewController () <SEGLotteryRantListDelegate,SEGActivityLotteryWinReocrdDelegate>

/// 是否展示过抽奖结果
@property (nonatomic, assign) BOOL hasShowResult;
/// 抽奖活动详情模型
@property (nonatomic, strong) SEGActivityLotteryDetailModel *lotteryDetailModel;
/// 抽奖结果模型
@property (nonatomic, strong) SEGActivityLotteryResultModel *lotteryResultModel;
/// 缓存砸金蛋抽奖视图
@property (nonatomic, assign) SEGActivityLotteryBreakEggsCell *tempEggCell;

@end

@implementation SEGActivityLotteryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 重置展示数据
    self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_Comment)];
    
    [self.tableView registerClass:[SEGActivityLotteryTurnTableCell class] forCellReuseIdentifier:kActivityLotteryTurnTableCellIdentifier];
    [self.tableView registerClass:[SEGActivityLotteryBreakEggsCell class] forCellReuseIdentifier:kActivityLotteryBreakEggsCellIdentifier];
    [self.tableView registerClass:[SEGActivityLotteryWinRecordCell class] forCellReuseIdentifier:kActivityLotteryWinRecordCellIdentifier];
    [self.tableView registerClass:[SEGActivityLotteryRankListCell class] forCellReuseIdentifier:kActivityLotteryRankListCellIdentifier];
    
    // 监听进入前台时重新开始砸金蛋的动画
    WeakSelf;
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] subscribeNext:^(NSNotification * notification) {
        if (weakSelf.tempEggCell) {
            [weakSelf.tempEggCell startHummerMoveAnimation];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 需要重新开始砸金蛋的动画
    if (self.tempEggCell) {
        [self.tempEggCell startHummerMoveAnimation];
    }
}

#pragma mark - 根据不同类型活动进行界面设置 子类根据需要重写
/// 请求详情后请求其他数据
- (void)requestOtherInfoAfterDetail {
    if ([self.detailModel.isReview isEqualToString:@"1"]) {//未开启留言板 不显示底部工具栏
        self.toolBarView.hidden = YES;
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    
    //请求抽奖活动主体
    [self.detailViewModel.requestLotteryDetailSignal subscribeNext:^(id  _Nullable x) {
        self.lotteryDetailModel = x;
        // 重置展示数据
        if (self.lotteryDetailModel.lotteryUsersSort.count > 0) {
            self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_Lottery), @(SEGActivityDetailCellDispalyType_LotteryTrends), @(SEGActivityDetailCellDispalyType_LotteryList), @(SEGActivityDetailCellDispalyType_Comment)];
        }else {
            self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_Lottery), @(SEGActivityDetailCellDispalyType_LotteryTrends), @(SEGActivityDetailCellDispalyType_Comment)];
        }
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

/// 返回section中的行数
- (NSInteger)setRowsInSection:(NSInteger)section {
    return 1;
}

/// 返回cell
- (UITableViewCell *)setCellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGActivityDetailCellDispalyType displayType = [self.displayTypeArray[indexPath.section] integerValue];
    if (displayType == SEGActivityDetailCellDispalyType_Lottery) {//大转盘或者砸金蛋抽奖界面
        SEGActivityLotteryType type = [self.lotteryDetailModel.lotteryType intValue];
        switch (type) {
            case SEGActivityLottery_BreakEggs://砸金蛋
            {
                SEGActivityLotteryBreakEggsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kActivityLotteryBreakEggsCellIdentifier forIndexPath:indexPath];
                cell.delegate = self;
                [cell setUpCellWithLotteryDetailModel:self.lotteryDetailModel actStatus:[self.detailModel.actStatus integerValue]];
                self.tempEggCell = cell;
                return cell;
                break;
            }
            default://大转盘
            {
                SEGActivityLotteryTurnTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kActivityLotteryTurnTableCellIdentifier forIndexPath:indexPath];
                cell.delegate = self;
                [cell setUpCellWithLotteryDetailModel:self.lotteryDetailModel actStatus:[self.detailModel.actStatus integerValue]];
                return cell;
                break;
            }
        }
    }
    if (displayType == SEGActivityDetailCellDispalyType_LotteryTrends) { //中奖动态
        SEGActivityLotteryWinRecordCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kActivityLotteryWinRecordCellIdentifier forIndexPath:indexPath];
        [cell setUpRecordCellWithLotteryDetailModel:self.lotteryDetailModel];
        return cell;
    }
    if (displayType == SEGActivityDetailCellDispalyType_LotteryList) { //排行榜
        SEGActivityLotteryRankListCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kActivityLotteryRankListCellIdentifier forIndexPath:indexPath];
        cell.delegate = self;
        [cell setUpCellWithLotteryDetailModel:self.lotteryDetailModel];
        return cell;
    }
    return [UITableViewCell new];
}

/// 设置cell高度
- (CGFloat)setHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}


#pragma mark - SEGLotteryRantListDelegate
- (void)showButtonAction {
    [self.tableView reloadData];
}

#pragma mark - SEGActivityLotteryWinReocrdDelegate
- (void)goToWinRecordViewController {
    SEGWinRecordListViewController* winRecordList = [[SEGWinRecordListViewController alloc] init];
    [self.navigationController pushViewController:winRecordList animated:YES];
}


- (void)lotteryBegin {
    self.hasShowResult = NO;
    
    [self.detailViewModel.participateLotterySignal subscribeNext:^(id  _Nullable x) {
        // 保存数据
        self.lotteryResultModel = x;
        // 获取抽奖cell下标
        __block NSInteger lotteryDispalyIndex = -1;
        [self.displayTypeArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.integerValue == SEGActivityDetailCellDispalyType_Lottery) {
                lotteryDispalyIndex = idx;
                *stop = YES;
            }
        }];
        // 未获取到抽奖cell下标的异常处理
        if (lotteryDispalyIndex == -1) {
            return;
        }
        
        SEGActivityLotteryType type = [self.lotteryDetailModel.lotteryType intValue];
        switch (type) {
            case SEGActivityLottery_BreakEggs://砸金蛋
            {
                SEGActivityLotteryBreakEggsCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:lotteryDispalyIndex]];
                BOOL hasWin = self.lotteryResultModel.notLotteryMsg.length > 0 ? NO : YES;//是否中奖
                [cell startAnimationWithResult:hasWin];
                //延迟弹出结果
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [self showLotteryResult];
                });
                break;
            }
            default://大转盘
            {
                SEGActivityLotteryTurnTableCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:lotteryDispalyIndex]];
                [cell startAnimationWithPrizeId:self.lotteryResultModel.prizeId];
            }
        }
    } error:^(NSError * _Nullable error) {
        if (error.code == kActicityErrorCode_NoAuth) {
            [self showNothAlterView];
            return;
        }
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

- (void)showLotteryResult {
    if (self.hasShowResult) {//防止动画多次回调
        return;
    }
    self.hasShowResult = YES;
    if ([self.lotteryDetailModel.freeLotterys integerValue] == 0) {//免费抽奖次数用完
        [SEGAlertView showTmepMessageWithMessage:[NSString stringWithFormat:@"-%@积分",self.lotteryDetailModel.price]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self seg_dealWithLotteryResult];
        });
    } else {
        [self seg_dealWithLotteryResult];
    }
}

- (void)seg_dealWithLotteryResult {
    SEGActivityLotteryResultModel *resultModel = self.lotteryResultModel;

    SEGAlerViewHUDType hudType;//弹窗类型
    BOOL hasWin = resultModel.notLotteryMsg.length > 0 ? NO : YES;//是否中奖
    NSString *picUrl = hasWin ? resultModel.prizePic : resultModel.notLotteryPic;
    
    //中奖结果弹窗
    SEGActivityLotteryType lotteryType = [self.lotteryDetailModel.lotteryType intValue];
    switch (lotteryType) {
        case SEGActivityLottery_BreakEggs://砸金蛋
        {
            if (hasWin) {
                hudType = SEGAlerViewHUDType_EggWinRecord;
            }else {
                hudType = SEGAlerViewHUDType_EggLose;
            }
            break;
        }
        default://大转盘
        {
            if (hasWin) {
                hudType = SEGAlerViewHUDType_TurnTableWinRecord;
            }else {
                hudType = SEGAlerViewHUDType_TurnTableLose;
            }
            break;
        }
    }

    __weak typeof (self) weakSelf = self;
    
    [SEGAlerViewHUD show:hudType prizeName:resultModel.prizeName picUrl:picUrl trytime:[resultModel.lotteryTimes integerValue] notLotteryMsg:resultModel.notLotteryMsg finished:^(SEGAlerViewHUDResult type) {
        //处理弹窗按钮回调
        switch (type) {
            case SEGAlerViewHUDResult_Know:/*我知道了*/
            {
                [self seg_refreshLotteryTimes];
                break;
            }
            case SEGAlerViewHUDResult_ShowPrize:/*查看奖励*/
            {
                SEGWinRecordListViewController* winRecordList = [[SEGWinRecordListViewController alloc] init];
                [weakSelf.navigationController pushViewController:winRecordList animated:YES];
                break;
            }
            case SEGAlerViewHUDResult_TryAgin:/*再来一次*/
            {
                [self seg_refreshLotteryTimes];
                break;
            }
            case SEGAlerViewHUDResult_WalletHistory:/*中奖记录*/
            {
                [self seg_refreshLotteryTimes];
                SEGWinRecordListViewController* winRecordList = [[SEGWinRecordListViewController alloc] init];
                [weakSelf.navigationController pushViewController:winRecordList animated:YES];
                break;
            }
            case SEGAlerViewHUDResult_LastTime:/*您的抽奖机会已用完！*/
            {
                [self seg_refreshLotteryTimes];
                break;
            }
            case SEGAlerViewHUDResult_Close:
            {
                [self seg_refreshLotteryTimes];
                break;
            }
        }
    }];

}

- (void)seg_refreshLotteryTimes {
    //刷新抽奖次数
    [self requestOtherInfoAfterDetail];
}

@end
